//
//  TWOViewController.m
//  jinling
//
//  Created by mac on 2018/9/21.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TWOViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>

#import "FenXiangView.h"

@interface TWOViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (strong, nonatomic) WKWebView *myWebView;
@property(nonatomic,strong)kongBaiye *kongBai;
@property(nonatomic,strong)UIImage *image;

@end

@implementation TWOViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKWebViewConfiguration* configuration = [[NSClassFromString(@"WKWebViewConfiguration") alloc] init];
    
    configuration.processPool = [WKProcessPool sharedProcessPool];
    [configuration.userContentController addScriptMessageHandler:self name:@"push"];
    [configuration.userContentController addScriptMessageHandler:self name:@"back"];
    
    if ([_url containsString:@"modify-head-face.html"]) {
        
        self.myWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, _mainW, _mainH) configuration:configuration];
    }else{        
        self.myWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, NAV_HEIGHT, _mainW, _mainH-NAV_HEIGHT) configuration:configuration];
    }

    self.myWebView.navigationDelegate = self;
    self.myWebView.UIDelegate=self;
    [self.view addSubview:self.myWebView];
    
    if ([_url containsString:@"modify-head-face.html"]) {
        self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, iPhoneX ? 48.f : 20.f, CGRectGetWidth(self.view.frame), 2) ];
        
    }
    else{
        self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, NAV_HEIGHT, CGRectGetWidth(self.view.frame), 2) ];
        
    }
    self.progressView.progressTintColor =_backgroundColor;
    [self.view addSubview:self.progressView];
    
    [self.myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    [self.myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden=NO;
    
}
-(void)viewWillAppear:(BOOL)animated{
    
    
    if ([_url containsString:@"modify-head-face.html"]) {
        
        
        self.navigationController.navigationBarHidden=YES;
    }

    
    NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
    
     NSURL *url;
    
    if (![_url containsString:@"kefu.ziyun.com.cn"]) {
        if (userDic!=nil) {
            NSString *oppenid=[userDic objectForKey:@"oppenid"];
            NSString *user_account=[userDic objectForKey:@"user_account"];
            if ([_url containsString:@"?"]){
                _url=[NSString stringWithFormat:@"%@&oppen_id=%@&user_account=%@",_url,oppenid,user_account];
            }
            else{
                _url=[NSString stringWithFormat:@"%@?oppen_id=%@&&user_account=%@",_url,oppenid,user_account];
            }
            
        }
        
        url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",_addressUrl,_url]];
    }
    
    else{
        self.navigationItem.title=@"在线客户";
        url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",_url]];
    }
    
   
   
    
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
    
    [self.myWebView loadRequest:mutableRequest];
    
}
#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    //加载进度值
    if ([keyPath isEqualToString:@"title"]){//网页title
        if (object == self.myWebView){
            self.navigationItem.title = self.myWebView.title;
            if ([self.myWebView.title isEqualToString:@"会员登录" ]) {
                [_kongBai shanChu];
                _kongBai=[kongBaiye new];
                [self.view addSubview:_kongBai];
                [_kongBai mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.right.bottom.mas_equalTo(0);
                    make.top.mas_equalTo(0);
                }];
                [_kongBai creatView];
                _kongBai.customSelectedBlock  = ^{
                    _loginWithVc(self);
                };
                
            }
            
            else{
                [_kongBai shanChu];
            }
        }
        else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
        
    }
    else if ([keyPath isEqual:@"estimatedProgress"] && object == self.myWebView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.myWebView.estimatedProgress animated:YES];
        if (self.myWebView.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:YES];
            }];
        }
    }
    else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    
    if ([message.name isEqualToString:@"push"]) {
        
        NSLog(@"%@",message.body);
        
        NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
        if (userDic!=nil) {
            if ([message.body containsString:@"goodsdetail.html"]) {
                NSString *user_id_number_state=[userDic objectForKey:@"user_id_number_state"];
                if (user_id_number_state.integerValue==0) {
                    shiMingViewController *shiming=[[shiMingViewController alloc] init];
                    shiming.cengsu=_cengsu+1;
                    shiming.isHave=YES;
                    shiming.url=@"page/id_number.html";
                    [gongju pushNextViewController:self andRootController:shiming];
                    return;
                }
            }
        }
        if ([message.body containsString:@"page/index"]) {
            self.navigationController.tabBarController.selectedIndex=0;
            [self.navigationController popToRootViewControllerAnimated:YES];
            return;
            
        }

        if ([message.body isEqualToString:@"logout"]) {
            NSFileManager *defaultManager = [NSFileManager defaultManager];
            if ([defaultManager removeItemAtPath:_userModelFile error:nil]) {
                
                
                if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
                    
                    NSSet *websiteDataTypes= [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,WKWebsiteDataTypeMemoryCache,]];
                    
                    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
                    
                    
                    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
                        [gongju svpInfo:@"退出登录成功"];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }];
                } else {
                    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                    
                    NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
                    
                    NSError *errors;
                    
                    BOOL remove=[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
                    if (remove) {
                        [gongju svpInfo:@"退出登录成功"];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }
                }
            }
            return;
        }

        if ([message.body containsString:@"modify-head-face.html"]) {
            [self userIconChange];
            return;
        }
        NSLog(@"%@",message.body);
        
        if ([message.body containsString:@"denglu"]) {
            _loginWithVc(self);
            return;
        }

        if ([message.body containsString:@"back"]) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        if ([message.body containsString:@"member-center"]) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }

        if (_cengsu==1) {
            TWOViewController *two=[[TWOViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==2) {
            ThreeViewController *two=[[ThreeViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==3) {
            FourViewController *two=[[FourViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==4) {
            FiveViewController *two=[[FiveViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==5) {
            SixViewController *two=[[SixViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
      two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==6) {
            SevenViewController *two=[[SevenViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==7) {
            EightViewController *two=[[EightViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==8) {
            NineViewController *two=[[NineViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==9) {
            TenViewController *two=[[TenViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
    }
    else if([message.name isEqualToString:@"back"]){
        [self.navigationController popViewControllerAnimated:YES];
    }

}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.progressView setProgress:0.0f animated:YES];

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    
    
    NSString *url = navigationAction.request.URL.absoluteString;
   
    
    if ([url containsString:@"page/index"]){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }

    
    else if ([url containsString:@"oodsdetail.html"]){
        
         UIBarButtonItem *pulishButton2=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"购物车3"] style:UIBarButtonItemStylePlain target:self action:@selector(pushToGouWu)];
        
        
        UIBarButtonItem *pulishButton3=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"分享"] style:UIBarButtonItemStylePlain target:self action:@selector(pushTofenXiang)];
        
        [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:pulishButton3,pulishButton2,nil]];
        
    }
    
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
}



-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    completionHandler();
}

-(void)pushToGouWu{
    if (_cengsu==1) {
        TWOViewController *two=[[TWOViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==2) {
        ThreeViewController *two=[[ThreeViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==3) {
        FourViewController *two=[[FourViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==4) {
        FiveViewController *two=[[FiveViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==5) {
        SixViewController *two=[[SixViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==6) {
        SevenViewController *two=[[SevenViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==7) {
        EightViewController *two=[[EightViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==8) {
        NineViewController *two=[[NineViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==9) {
        TenViewController *two=[[TenViewController alloc] init];
        two.url=@"page/shopping-cart.html";
        two.cengsu=_cengsu+1;
        two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    
    
}
-(void)pushTofenXiang{

    FenXiangView *fenxiang=[FenXiangView new];
    [self.view addSubview:fenxiang];
    [fenxiang mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    fenxiang.themID=[NSString stringWithFormat:@"%@/%@",_addressUrl,_url];
    fenxiang.kLinkTitle=self.myWebView.title;
    fenxiang.kLinkDescription=@"";
    [fenxiang creatView];
}



- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    
    completionHandler(NO);
}


//可以识别多个手势
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}


-(void) userIconChange{
    
    
    
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle: @"" message: @"拍照或从相册中选择" preferredStyle: UIAlertControllerStyleActionSheet];
    
    [actionSheetController addAction: [UIAlertAction actionWithTitle:@"打开相册"style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [self LocalPhoto];
        
    }]];
    [actionSheetController addAction: [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
        [self locaXiangJi];
        
        
    }]];
    
    [actionSheetController addAction: [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {}]];
    
    [self presentViewController: actionSheetController animated:YES completion:^{}];
    
}

-(void)locaXiangJi{
    
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    UIImagePickerControllerQualityType qualityType = UIImagePickerControllerQualityTypeHigh;
    
    /*判断是否有相机*/
    
    if([UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypeCamera]){
        
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        
        picker.delegate=self;
        
        /*设置拍照后的图片可被编辑*/
        
        picker.allowsEditing=YES;
        
        /*资源类型为照相机*/
        
        picker.sourceType= sourceType;
        
        /*品质为高*/
        
        picker.videoQuality= qualityType;
        
        [self presentViewController: picker animated:YES completion:^{
            
            
        }];
        
    }else{
        //        [self alertTitle:@"该设备无摄像头"];
        
    }
    
}
-(void)LocalPhoto
{
    
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    
    /*资源类型为图片库*/
    
    picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    
    picker.delegate=self;
    
    /*设置选择后的图片可被编辑*/
    
    picker.allowsEditing=YES;
    
    [self presentViewController:picker animated:YES completion:^{
        
        
    }];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        self->_image=image;
        [self shangchuan];
    }];
    
}

-(void)shangchuan{
    
    NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
    NSString *user_id=[userDic objectForKey:@"oppenid"];
    NSString *user_account=[userDic objectForKey:@"user_account"];
    
    
    NSString *name=[NSString stringWithFormat:@"%@_%@%d.png",user_id,[gongju curTimeString],0];
    
    
    NSMutableArray *imageArr=[NSMutableArray arrayWithCapacity:0];
    NSDictionary *dic3=[NSDictionary dictionaryWithObjectsAndKeys:_image,@"image",@"file",@"fileName",name,@"name", nil];
    [imageArr addObject:dic3];
    
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:name,@"head_image",user_id,@"oppen_id",user_account,@"user_account", nil];
    [gongju afnPostImageWithDict:dic WithAddressUrl:@"page/changeHeadImg.html" withImageArr:imageArr withFileName:nil fileOrImg:@"image" WithViewController:self success:^(id responseObject) {      
        [self.myWebView reload];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
